<template>
  <div class="simple-file-upload">
    <!-- 未上传状态 - 显示+号按钮 -->
    <div
      v-if="!currentFile"
      class="upload-card upload-card--empty"
      :class="{ 'upload-card--disabled': disabled }"
    >
      <a-upload
        :before-upload="handleBeforeUpload"
        :accept="accept"
        :show-upload-list="false"
        :disabled="disabled"
      >
        <div class="upload-content">
          <div class="upload-icon">
            <LoadingOutlined v-if="uploading" class="loading-icon" />
            <PlusOutlined v-else />
          </div>
          <div class="upload-text">
            {{ uploading ? '上传中' : buttonText }}
          </div>
        </div>
      </a-upload>
    </div>

    <!-- 已上传状态 - 显示文件信息和删除按钮 -->
    <div
      v-else
      class="upload-card upload-card--filled"
    >
      <div class="file-info">
        <div class="file-icon">
          <FileTextOutlined />
        </div>
        <div class="file-details">
          <div class="file-name" :title="currentFile.name">
            {{ currentFile.name }}
          </div>
          <div class="file-status">
            <CheckCircleOutlined class="status-icon" />
            上传成功
          </div>
        </div>
      </div>
      <div class="file-actions">
        <a-button
          type="text"
          size="small"
          @click="handlePreview"
          class="action-btn preview-btn"
          v-if="showPreview"
        >
          <EyeOutlined />
        </a-button>
        <a-button
          type="text"
          size="small"
          danger
          @click="handleRemove"
          class="action-btn remove-btn"
        >
          <DeleteOutlined />
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  LoadingOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons-vue'

interface SimpleFileUploadProps {
  modelValue?: string // 当前文件路径
  accept?: string // 接受的文件类型
  buttonText?: string // 按钮文字
  disabled?: boolean // 是否禁用
  uploadUrl?: string // 上传接口地址
  maxSize?: number // 最大文件大小（MB）
  allowedTypes?: string[] // 允许的文件类型数组
  showPreview?: boolean // 是否显示预览按钮
  width?: string // 组件宽度
  height?: string // 组件高度
}

interface SimpleFileUploadEmits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
  (e: 'success', response: any, file: File): void
  (e: 'error', error: any, file: File): void
  (e: 'preview', filePath: string): void
  (e: 'remove', filePath: string): void
}

const props = withDefaults(defineProps<SimpleFileUploadProps>(), {
  accept: '',
  buttonText: '选择文件',
  disabled: false,
  uploadUrl: '/api/upload',
  maxSize: 10,
  allowedTypes: () => [],
  showPreview: false,
  width: '120px',
  height: '120px'
})

const emit = defineEmits<SimpleFileUploadEmits>()

// 状态管理
const uploading = ref(false)
const currentFile = ref<any>(null)

// 根据modelValue生成文件信息
const generateFileInfo = (filePath: string | undefined) => {
  if (!filePath) return null

  return {
    name: filePath.split('/').pop() || '未知文件',
    path: filePath,
    url: filePath
  }
}

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newValue) => {
    currentFile.value = generateFileInfo(newValue)
  },
  { immediate: true }
)

// 文件大小验证
const validateFileSize = (file: File): boolean => {
  const sizeMB = file.size / 1024 / 1024
  if (sizeMB > props.maxSize) {
    message.error(`文件大小不能超过 ${props.maxSize}MB`)
    return false
  }
  return true
}

// 文件类型验证
const validateFileType = (file: File): boolean => {
  if (props.allowedTypes.length > 0) {
    const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
    if (!props.allowedTypes.includes(fileExtension)) {
      message.error(`只允许上传以下类型的文件: ${props.allowedTypes.join(', ')}`)
      return false
    }
  }
  return true
}

// 上传前的处理
const handleBeforeUpload = async (file: File) => {
  // 文件验证
  if (!validateFileSize(file) || !validateFileType(file)) {
    return false
  }

  try {
    uploading.value = true

    // 模拟上传（可以替换为真实的上传逻辑）
    const uploadPath = await simulateUpload(file)

    // 更新文件路径
    emit('update:modelValue', uploadPath)
    emit('change', uploadPath)
    emit('success', { filePath: uploadPath }, file)

    message.success(`文件 ${file.name} 上传成功`)
  } catch (error) {
    console.error('文件上传失败:', error)
    emit('error', error, file)
    message.error(`文件 ${file.name} 上传失败`)
  } finally {
    uploading.value = false
  }

  return false // 阻止默认上传行为
}

// 模拟上传函数
const simulateUpload = async (file: File): Promise<string> => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000))

  // 生成模拟的文件路径
  const timestamp = Date.now()
  return `/uploads/${timestamp}_${file.name}`
}

// 预览文件
const handlePreview = () => {
  if (currentFile.value) {
    emit('preview', currentFile.value.path)
  }
}

// 移除文件
const handleRemove = () => {
  const filePath = currentFile.value?.path

  emit('update:modelValue', '')
  emit('change', '')
  emit('remove', filePath || '')

  message.success('文件已移除')
}
</script>

<style scoped>
.simple-file-upload {
  display: inline-block;
  width: v-bind(width);
  height: v-bind(height);
}

/* 上传卡片基础样式 */
.upload-card {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

/* 空状态卡片 */
.upload-card--empty {
  border: 2px dashed #d9d9d9;
  background: #fafafa;
  cursor: pointer;
}

.upload-card--empty:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.upload-card--empty:hover .upload-icon {
  color: #1890ff;
  transform: scale(1.1);
}

.upload-card--disabled {
  opacity: 0.6;
  cursor: not-allowed;
  border-color: #d9d9d9;
  background: #f5f5f5;
}

.upload-card--disabled:hover {
  border-color: #d9d9d9;
  background: #f5f5f5;
}

/* 已填充状态卡片 */
.upload-card--filled {
  border: 1px solid #52c41a;
  background: #f6ffed;
  display: flex;
  flex-direction: column;
  padding: 8px;
}

/* 上传触发器 */
.upload-card--empty :deep(.ant-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 上传内容 */
.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  user-select: none;
  height: 100%;
  padding: 8px;
}

.upload-icon {
  font-size: 24px;
  color: #8c8c8c;
  margin-bottom: 4px;
  transition: all 0.3s ease;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.upload-text {
  font-size: 12px;
  color: #8c8c8c;
  line-height: 1.2;
}

/* 文件信息区域 */
.file-info {
  flex: 1;
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}

.file-icon {
  font-size: 16px;
  color: #1890ff;
  margin-right: 6px;
  flex-shrink: 0;
  margin-top: 2px;
}

.file-details {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 12px;
  color: #262626;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.3;
  font-weight: 500;
}

.file-status {
  display: flex;
  align-items: center;
  font-size: 10px;
  color: #52c41a;
  line-height: 1.2;
}

.status-icon {
  margin-right: 2px;
  font-size: 10px;
}

/* 操作按钮区域 */
.file-actions {
  display: flex;
  justify-content: flex-end;
  gap: 4px;
}

.action-btn {
  padding: 2px 4px;
  height: auto;
  min-height: auto;
  border: none;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: scale(1.1);
}

.preview-btn:hover {
  color: #1890ff !important;
  background: rgba(24, 144, 255, 0.1);
}

.remove-btn:hover {
  color: #ff4d4f !important;
  background: rgba(255, 77, 79, 0.1);
}

/* 不同尺寸的适配 */
.simple-file-upload[style*="width: 80px"] .upload-icon {
  font-size: 20px;
}

.simple-file-upload[style*="width: 80px"] .upload-text {
  font-size: 10px;
}

.simple-file-upload[style*="width: 80px"] .file-name {
  font-size: 10px;
}

.simple-file-upload[style*="width: 80px"] .file-status {
  font-size: 9px;
}

/* 动画效果 */
.upload-card--filled {
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 悬停效果 */
.upload-card--filled:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}
</style>